#-*-coding:utf-8-*-
import os
import hou

root=hou.node("/obj")
shop=hou.node("/shop")
# mata=shop.createNode('arnold_vopnet','mata')
# sf=mata.createNode('arnold::standard_surface')
# imga=mata.createNode('arnold::image')



def fileNameType(filepath):
    filepath,temfilename=os.path.split(filepath)
    return temfilename

# check mat
def ismatexis(matname):
    matlist = hou.node('/mat').children()
    A = 0
    for n in matlist:
        # print n.name()
        if n.name() == matname:
            A += 1
        else:
            pass
    return A


def getMatInfo(path):
    jsonfile = open(path, 'r')
    poly_matDic = {}
    mat_pathDic = {}
    AllMatList = {}
    try:
        # getJson= str(json.load(jsonfile)).encode('utf-8').decode('unicode_escape')
        getJson = eval(jsonfile.read())
        poly_matDic = getJson['poly_matDic']
        mat_pathDic = getJson['mat_pathDic']
        AllMatList = getJson['AllMatList']
    # print AllMatList
    except Exception as getMatInfo_ERR:
        print('wrong')
        print(str(getMatInfo_ERR))

    finally:
        jsonfile.close()

    return (poly_matDic, mat_pathDic, AllMatList)



def _createArnoldShader(shaderName,data):
    """
    传入材质名称与材质数据，返回arnold network 而不是里面的shader
    :param shaderName:
    :param data:
    :return:
    """

    shader=None
    if data:
        exised_shaders = [c.name() for c in shop.children()]
        shader_type=data['shader_type']
        if shader_type=='aiStandardSurface':
            if shaderName not in exised_shaders:
                shader=shop.createNode('arnold_vopnet',shaderName)
                out_material=shader.children()[0]
                ss=shader.createNode('arnold::standard_surface')
                out_material.setNamedInput('surface',ss,'shader')
                attr=data['attr']
                parms_list=[n.name() for n in ss.parms()]   #节点参数名称，用来设置值
                portnames=[p for p in ss.inputNames()]  #节点端口名称,用来连接端口
                print('shaderName parms_list:',parms_list)
                for par,value in attr.items():
                    if par in parms_list:
                        ss.parm(par).set(value)

                paths=data['path']
                if paths:
                    for k,v in paths.items():
                        if k in portnames:
                            img=shader.createNode('arnold::image')
                            img.parm('filename').set(v)
                            ss.setNamedInput(k,img,'rgba')

    return shader





def mayaToHoudini(*args):
    # create materials
    getJsonFilePath = hou.pwd().parm('matinfo').evalAsString()
    info = getMatInfo(getJsonFilePath)
    poly_matDic = info[0]
    mat_pathDic = info[1]
    AllMatList = info[2]

    #生成Arnold材质
    if mat_pathDic:
        for k,v in mat_pathDic.items():
            shader=_createArnoldShader(k,v)


    # create new geo by ABC
    getAbcpath = hou.pwd().parm('abcpath').evalAsString()
    nodePaths = getAbcpath.split(' ')
    # .rawValue()
    abc = hou.node(getAbcpath)
    name = abc.name()
    newName = name + 'Geo'
    Geo = hou.node('/obj').createNode('geo', newName)  #生成对应Geo
    abcChildren1 = abc.children()
    for ax in abcChildren1:  #abc第一层级所有alembicxform子节点
        geos=ax.children()
        geo_name=ax.name()
        for g in geos:  #第二层级所有geo节点,这个居然是shape名称命名的geo,正常情况下只有一个geo
            if g.type().name()=='geo':  #仅对geo进行操作。
                polyname = g.name()
                print(polyname)
                matchmatname = poly_matDic[geo_name]    #获取对应材质名称
                matnodepath = '/shop/' + matchmatname   #获取材质节点
                alembic = g.children()[0]       #第三层级所有alembic子节点，因为导出时是选中，所以一般只有一个
                # abcChildren1geo1shape = abcChildren1geo.children()[0]
                abcChildren1geo1shapePath = alembic.path()
                abcChildren1geo1shapeName = alembic.name()

                objmerge = Geo.createNode('object_merge', 'object_merge' + abcChildren1geo1shapeName)
                objmerge.parm('objpath1').set(abcChildren1geo1shapePath)
                objmerge.parm('xformtype').set(1)
                objmergePos = objmerge.position()

                convert = Geo.createNode('convert', 'convert' + abcChildren1geo1shapeName)
                convert.setPosition(hou.Vector2(objmergePos[0], objmergePos[0] - 1))
                convert.setInput(0, objmerge)
                convert.setGenericFlag(hou.nodeFlag.Bypass, 1)

                matnode = Geo.createNode('material', 'material' + abcChildren1geo1shapeName)

                matnode.parm('shop_materialpath1').set(matnodepath)

                matnode.setPosition(hou.Vector2(objmergePos[0], objmergePos[0] - 2))
                matnode.setInput(0, convert)

    hou.ui.displayMessage('OK')